import { login, logout, getInfo, accountLogout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { http_login_account, http_login_code } from '@/api/login'
import {Message} from "element-ui";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERID: (state, userId) => {
    state.userId = userId
  },
  SET_ROLENAME: (state, roleNames) => {
    state.roleNames = roleNames
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo

     let p = new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        commit('SET_USERID',data.userId)
        commit('SET_NAME', data.userName)
        commit('SET_ROLENAME', data.roleNames)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
    return p
  },

  getLoginUserInfo({ commit }, code) {
    let p = new Promise((resolve, reject) => {
      http_login_code(code).then(response => {
        const { data} = response
        localStorage.setItem("user",JSON.stringify(data))
        commit('SET_TOKEN', data.token)
        commit('SET_USERID',data.userId)
        commit('SET_NAME', data.userName)
        commit('SET_BUTTONS', data.buttons)
        commit('SET_ROLENAME', data.roleNames)

        setToken(data.token)
        resolve()
      }).catch(error => {
        Message.error("扫码登录失败")
        reject(error)
      })
    })
    return p
  },

  getLoginUserInfoByAccount({ commit }, data) {
    let p = new Promise((resolve, reject) => {
      http_login_account(data).then(response => {
        const { data} = response
        localStorage.setItem("user",JSON.stringify(data))
        commit('SET_TOKEN', data.token)
        commit('SET_USERID',data.userId)
        commit('SET_NAME', data.userName)
        commit('SET_BUTTONS', data.buttons)
        commit('SET_ROLENAME', data.roleNames)

        if (data.token != null || data.token != ''){
          setToken(data.token)
        }
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
    return p
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {avatar } = data

        commit('SET_NAME', (JSON.parse(localStorage.getItem('user'))).userName)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // let userId = JSON.parse(localStorage.getItem("user")).userId
      let user = JSON.parse(localStorage.getItem("user"))
      let userId = user.userId
      if (userId) {
        logout(userId).then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        }).catch(error => {
          reject(error)
        })
      }else {
        let accountNumber = user.accountNumber
        accountLogout(accountNumber).then(() => {
          removeToken() // must remove  token  first
          resetRouter()
          commit('RESET_STATE')
          resolve()
        }).catch(error => {
          reject(error)
        })
      }
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

